<template>
  <SearchForm :query="query" @search="onSearch" @reset="handleReset" />

  <n-space class="py-[10px]" justify="end">
    <n-button
      ghost
      type="error"
      size="small"
      v-hasPermi="['system:user:remove']"
      :disabled="checkedRows.length === 0"
      @click="handleDeleteUsers"
    >
      <template #icon>
        <n-icon size="18"><DeleteOutlineOutlined /></n-icon>
      </template>
      删除
    </n-button>
    <n-button
      ghost
      type="success"
      size="small"
      :loading="downloadLoading"
      v-hasPermi="['system:user:export']"
      @click="handleExport"
    >
      <template #icon>
        <n-icon size="18"><FileUploadOutlined /></n-icon>
      </template>
      导出
    </n-button>
    <n-button
      ghost
      type="success"
      size="small"
      v-hasPermi="['system:user:import']"
      @click="openUploadDialog"
    >
      <template #icon>
        <n-icon size="18"><FileDownloadOutlined /></n-icon>
      </template>
      导入
    </n-button>
    <n-button
      ghost
      type="primary"
      size="small"
      v-hasPermi="['system:user:add']"
      @click="openDialog"
    >
      <template #icon>
        <n-icon size="18"><PlusRound /></n-icon>
      </template>
      新增
    </n-button>
  </n-space>

  <n-data-table
    ref="tableRef"
    :loading="loading"
    :columns="columns"
    :data="tableData"
    :row-key="(row: any) => row.userId"
    :pagination="{
      page: query.page,
      pageSize: query.pageSize,
      itemCount: total,
      showSizePicker: true,
      onUpdatePage: handlePageChange,
      onUpdatePageSize: handlePageSizeChange,
    }"
    @update:checked-row-keys="handleChcekedRowKeys"
  />

  <!-- 新增、修改用户弹窗 -->
  <UpdateUserDialog :visible="visible" :data="data" @close="handleCloseDialog"></UpdateUserDialog>

  <!-- 重置密码弹窗 -->
  <ResetPasswordDialog
    :visible="resetPasswordVisible"
    :data="resetPasswordData"
    @close="closeResetPasswordDialog"
  ></ResetPasswordDialog>

  <!-- 上传导入文件弹窗 -->
  <Upload :visible="uploadDialogVisible" @close="uploadDialogClose" />
</template>

<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import SearchForm from './components/SearchForm.vue';
import { useTable } from '@/hooks/useTable';
import {
  NButton,
  NPopconfirm,
  NSpace,
  NSwitch,
  useMessage,
  useDialog as useConfirmDialog,
} from 'naive-ui';
import {
  DeleteOutlineOutlined,
  FileDownloadOutlined,
  FileUploadOutlined,
  PlusRound,
} from '@vicons/material';
import UpdateUserDialog from './components/UpdateUserDialog.vue';
import { useDialog } from '@/hooks/useDialog';
import { changeUserStatus, deleteUser, getUserList } from '@/apis/system/user';
import ResetPasswordDialog from './components/ResetPasswordDialog.vue';
import { useRouter } from 'vue-router';
import { useDownload } from '@/hooks/useDownload';
import Permisstion from '@/components/permission/index.vue';
import Upload from './components/Upload.vue';
import { getColumns } from './columns';

defineOptions({
  name: 'User',
});

const IconComp = ref<any>(null);

/**
 * 自动动态加载图标组件：
 * icon = "F7TimerFill"
 * pack = "ionicons5" → 实际路径：@vicons/ionicons5
 */
onMounted(async () => {
  try {
    const mod = await import(`@vicons/material`);
    IconComp.value = mod['AcUnitFilled'];
  } catch (err) {
    console.error(`图标加载失败:`, err);
  }
});

const message = useMessage();
const router = useRouter();
const checkedRows = ref<any[]>([]);
const dialog = useConfirmDialog();
const { download, loading: downloadLoading } = useDownload();
const {
  query,
  tableData,
  total,
  loading,
  handleSearch,
  handleReset,
  handlePageChange,
  handlePageSizeChange,
} = useTable({
  api: getUserList,
  defaultQuery: {
    userName: null,
    phonenumber: null,
    status: null,
    'params[beginTime]': null,
    'params[endTime]': null,
  },
});

const { visible, data, openDialog, closeDialog } = useDialog();

// 上传导入文件弹窗
const {
  visible: uploadDialogVisible,
  openDialog: openUploadDialog,
  closeDialog: uploadDialogClose,
} = useDialog();

// 重置密码弹窗
const {
  visible: resetPasswordVisible,
  data: resetPasswordData,
  openDialog: openResetPasswordDialog,
  closeDialog: closeResetPasswordDialog,
} = useDialog();

// 查询表单提交
const onSearch = (values: any) => {
  Object.assign(query, values, { pageNum: 1 });
  handleSearch();
};

/**
 * 关闭弹窗回调
 * @param params
 */
const handleCloseDialog = (params: any) => {
  if (params?.needRefresh) {
    handleSearch();
  }
  closeDialog();
};

const columns = getColumns({
  enableOrEnable,
  openDialog,
  openResetPasswordDialog,
  handleRole,
  handleDeleteUser,
});

/**
 * 多删，删除选中的用户
 * @param selectedUsers
 */
async function handleDeleteUsers() {
  const userIds = checkedRows.value.map((item: any) => item.userId).join(',');
  const userName = checkedRows.value.map((item: any) => item.userName).join(',');

  dialog.warning({
    title: '删除用户',
    content: `确定要删除选中的 ${userName} 用户吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const res: any = await deleteUser(userIds);
      if (res.code === 200) {
        message.success('删除成功');
        handleSearch();
        checkedRows.value = []; // reset选中状态
      }
    },
  });
}

/**
 * 单个删除
 * @param row
 */
async function handleDeleteUser(row: any) {
  try {
    const res: any = await deleteUser(row.userId);
    if (res.code === 200) {
      message.success('删除成功');
      handleSearch();
    }
  } catch (error) {}
}

function handleChcekedRowKeys(keys: Array<string | number>, rows: object[]) {
  checkedRows.value = rows;
}

/**
 * 停用启用handler
 * @param row
 */
async function enableOrEnable(row: any) {
  row.switchLoading = true;
  let text = row.status === '0' ? '停用' : '启用';
  const res: any = await changeUserStatus({
    userId: row.userId,
    status: row.status === '0' ? '1' : '0',
  });
  if (res.code === 200) {
    message.success(`${text}成功`);
    row.status = row.status === '0' ? '1' : '0';
  } else {
    message.error(`${text}失败`);
  }
  row.switchLoading = false;
}

/**
 * 导出
 */
function handleExport() {
  download('/user/export', { ...query }, `user_${new Date().getTime()}.xlsx`);
}

// 分配角色页
function handleRole(row: any) {
  router.push(`/system/user-auth/role/${row.userId}`);
}
</script>

<style scoped lang="less"></style>
